﻿#region Using

using System;
using System.Linq;
using System.Text.RegularExpressions;

using GameCommon.Args;
using GameCommon.Manager;

using Microsoft.Xna.Framework.Input;

#endregion

namespace Menu.Common
{
    internal class InputController : IDisposable
    {
        public InputController()
        {
            Managers.KeyboardManager.KeyPressed += this.OnKeyPressed;
        }

        public bool IsActive { get; private set; }

        public string Input { get; private set; }

        /// <summary>
        ///     Removes Event
        /// </summary>
        public void Dispose()
        {
            Managers.KeyboardManager.KeyPressed -= this.OnKeyPressed;
        }

        public void Begin(string value)
        {
            this.IsActive = true;
            this.Input = value;
        }

        public void End()
        {
            this.IsActive = false;
        }

        private void OnKeyPressed(KeyboardArgs args)
        {
            if (!this.IsActive)
            {
                return;
            }

            if (args.Key == Keys.Back && this.Input.Length > 0)
            {
                this.Input = this.Input.Substring(0, this.Input.Length - 1);
                return;
            }

            var keyString = args.Key.ToString();

            if (Regex.IsMatch(keyString, "^[a-zA-Z]$"))
            {
                if (args.Modifiers.Contains(Keys.LeftShift) || args.Modifiers.Contains(Keys.RightShift))
                {
                    this.Input += keyString.ToUpper();
                    return;
                }

                this.Input += keyString.ToLower();
            }
        }
    }
}